import { ElMessage } from 'element-plus'

// API 基础配置 - 使用环境变量或默认值
const API_BASE_URL = (import.meta.env.VITE_API_BASE_URL || '').replace(/\/$/, '') + '/admin'

// 通用请求函数
export const useApi = () => {

  const request = async (url, options = {}) => {
    const {
      method = 'POST',
      data = null,
      headers = {},
      showError = true
    } = options

    try {
      // 获取存储的token
      const token = localStorage.getItem('admin_token')

      const config = {
        method,
        headers: {
          'Content-Type': 'application/json',
          ...(token && { 'Authorization': `Bearer ${token}` }),
          ...headers
        }
      }

      if (data) {
        config.body = JSON.stringify(data)
      }

      const response = await fetch(`${API_BASE_URL}${url}`, config)
      const result = await response.json()

      // 如果返回401，清除token并跳转到登录页
      if (response.status === 401) {
        localStorage.removeItem('admin_token')
        localStorage.removeItem('admin_user')
        if (window.location.pathname !== '/admin/login') {
          window.location.href = '/admin/login'
        }
      }

      return result
    } catch (error) {
      console.error('Request error:', error)
      if (showError) {
        ElMessage.error('网络请求失败')
      }
      throw error
    }
  }

  // 症状分类 API
  const symptomCategoryApi = {
    // 获取列表
    getList: (params) => request('/symptom_category/index', { data: params }),

    // 获取单个
    getById: (id) => request('/symptom_category/read', { data: { id } }),

    // 创建
    create: (data) => request('/symptom_category/save', { data }),

    // 更新
    update: (data) => request('/symptom_category/update', { data }),

    // 删除
    delete: (id) => request('/symptom_category/delete', { data: { id } }),

    // 批量删除
    batchDelete: (ids) => request('/symptom_category/deleteMultiple', { data: { ids } }),

    // 获取启用的分类列表
    getActiveList: () => request('/symptom_category/getActiveList', { data: {} }),

    // 更新排序
    updateSort: (data) => request('/symptom_category/updateSort', { data })
  }

  // 症状 API
  const symptomApi = {
    // 获取列表
    getList: (params) => request('/symptom/index', { data: params }),

    // 获取单个
    getById: (id) => request('/symptom/read', { data: { id } }),

    // 创建
    create: (data) => request('/symptom/save', { data }),

    // 更新
    update: (data) => request('/symptom/update', { data }),

    // 删除
    delete: (id) => request('/symptom/delete', { data: { id } }),

    // 批量删除
    batchDelete: (ids) => request('/symptom/deleteMultiple', { data: { ids } }),

    // 根据分类ID获取症状
    getByCategoryId: (categoryId) => request('/symptom/getByCategoryId', { data: { category_id: categoryId } }),

    // 获取启用的症状列表（按分类分组）
    getActiveList: () => request('/symptom/getActiveList', { data: {} })
  }

  // 汤药 API
  const formulaApi = {
    // 获取列表
    getList: (params) => request('/formula/index', { data: params }),

    // 获取单个
    getById: (id) => request('/formula/read', { data: { id } }),

    // 创建
    create: (data) => request('/formula/save', { data }),

    // 更新
    update: (data) => request('/formula/update', { data }),

    // 删除
    delete: (id) => request('/formula/delete', { data: { id } }),

    // 批量删除
    batchDelete: (ids) => request('/formula/deleteMultiple', { data: { ids } }),

    // 根据症状查找汤药
    findBySymptoms: (symptomDesc) => request('/formula/findBySymptoms', { data: { symptom_desc: symptomDesc } }),

    // 获取统计信息
    getStatistics: () => request('/formula/getStatistics', { data: {} })
  }

  // 仪表盘 API
  const dashboardApi = {
    // 获取统计数据
    getStatistics: () => request('/dashboard/getStatistics', { data: {} }),

    // 获取最近症状
    getRecentSymptoms: (limit = 5) => request('/dashboard/getRecentSymptoms', { data: { limit } }),

    // 获取最近汤药
    getRecentFormulas: (limit = 5) => request('/dashboard/getRecentFormulas', { data: { limit } }),

    // 获取综合概览
    getOverview: () => request('/dashboard/getOverview', { data: {} }),

    // 获取系统健康状态
    getSystemHealth: () => request('/dashboard/getSystemHealth', { data: {} })
  }

  // 认证 API
  const authApi = {
    // 管理员登录
    login: (username, password) => request('/auth/login', {
      data: { username, password },
      showError: false // 登录错误由组件处理
    }),

    // 管理员退出
    logout: () => request('/auth/logout', { data: {} }),

    // 验证会话
    verify: () => request('/auth/verify', { data: {} }),

    // 修改密码
    changePassword: (oldPassword, newPassword, confirmPassword) => request('/auth/changePassword', {
      data: {
        old_password: oldPassword,
        new_password: newPassword,
        confirm_password: confirmPassword
      }
    })
  }

  // 数据同步 API
  const dataSyncApi = {
    // 导入症状数据
    importSymptoms: (data) => request('/data_sync/importSymptoms', { data: { data } }),

    // 导入汤药数据
    importFormulas: (data) => request('/data_sync/importFormulas', { data: { data } })
  }

  return {
    request,
    symptomCategoryApi,
    symptomApi,
    formulaApi,
    dashboardApi,
    authApi,
    dataSyncApi
  }
}
